import * as fs from "fs";
import * as os from "os";
import * as vscode from "vscode";

import adrequest from "./util/adrequest";
import { DOMAIN, orgThreadsUrl, IMAGE, IMAGE_THUMB } from "./util/apis";

function sucess(decodedData: any): void {
  let mdData = '';
  for (let i = 0; i < decodedData.length; i++) {
    const thread = decodedData[i];
    mdData += `***\r\n` +
      `${thread.title} ${thread.name} ${thread.now} >>No.${thread.id}\r\n` +
      (thread.img ? `\r\n![分享图片](${IMAGE_THUMB + thread.img + thread.ext})[查看大图](${IMAGE + thread.img + thread.ext})\r\n` : '') +
      `\`\`\`\r\n` +
      `${thread.content}\r\n` +
      `\`\`\`\r\n`;
  }

  fs.writeFile(os.tmpdir() + '/板块.md', mdData, 'utf-8', (err) => {
    if (err) {
      console.error(err);
      throw err;
    }
    console.log(`${os.tmpdir()}/板块.md 写入成功`);
    const a = vscode.Uri.file(os.tmpdir() + '/板块.md');
    vscode.window.showTextDocument(a);
    vscode.window.showInformationMessage("板块打开成功！");
  });
}
export default async function threads() {
  const result = await vscode.window.showInputBox({
    placeHolder: '请输入指定板块的ID与页数，使用空格分割，比如综合1"4 1"'
  });
  let resultValid = /^(\d+) (\d+)$/;
  if (!result || !resultValid.test(result)) {
    return vscode.window.showErrorMessage("请正确输入！");
  }
  let [id, page] = result.split(' ');
  adrequest(DOMAIN + orgThreadsUrl(id, page), sucess, (e: Error) => {
    vscode.window.showErrorMessage(e.message);
  });
}